package com.example.demo.handler;

import com.example.demo.entity.CustomUser;
import com.example.demo.entity.User;
import com.example.demo.service.UserStatusService;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.ResponseResult;
import com.example.demo.utils.SpringContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.example.demo.utils.Constants.EXPIRATION_TIME;

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    private final StringRedisTemplate stringRedisTemplate;

    public MyAuthenticationSuccessHandler(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        CustomUser user = (CustomUser) authentication.getPrincipal();
        response.setContentType("application/json;charset=UTF-8");
        String token = new JwtUtil().generateToken(user.getUsername());
        stringRedisTemplate.opsForValue().set("user:token:" + token, user.getUsername(), EXPIRATION_TIME, TimeUnit.MILLISECONDS);
        //更新用户状态为在线
        SpringContext.getBean(UserStatusService.class).userOnline(user.getUser().getUserId());
        User user1 = user.getUser();
        user1.filter();
        user1.setToken(token);
        ResponseResult<User> result = ResponseResult.success(user1);
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }
}
